package com.dl.mian.http;

import androidx.annotation.CallSuper;


import com.dl.mian.http.model.HttpResult;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public abstract class DataObserver<T extends HttpResult> implements Observer<T> {

    @Override
    public void onSubscribe(Disposable d) {
    }

    @Override
    public final void onNext(T o) {
        HttpResult<Object> result = (HttpResult<Object>) o;
        if ("200".equals(result.getCode())||"0".equals(result.getCode())) {
            success(o);
        } else {
//            if("401".equals(result.getCode())){
//                ActivityUtils.startActivity(LoginActivity.class);
//            }
            fail(result);
        }
    }

    @Override
    public final void onError(Throwable e) {
        String msg = e.getMessage();
        try {
            HttpResult httpResult = GsonUtil.gson().fromJson(msg, HttpResult.class);
            fail(httpResult);
        } catch (Exception e1) {
            error(e);
        }
    }

    @Override
    public final void onComplete() {
        complete();
    }

    // 下面几个函数子类强制调用super.XXX()
    @CallSuper
    public void success(T o) {
    }

    /**
     * 单纯的异常
     *
     * @param e
     */
    @CallSuper
    public void error(Throwable e) {
    }

    /**
     * 业务需要处理的错误
     *
     * @param result
     */
    @CallSuper
    public void fail(HttpResult result) {
    }

    @CallSuper
    public void complete() {
    }
}
